<template>
  <div class="account-box">
    <div class="toggle">
      <a @click="isMsgLogin = false" href="javascript:;" v-if="isMsgLogin">
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
      <a @click="isMsgLogin = true" href="javascript:;" v-else>
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
    </div>
    <!-- form表单start -->
    <Form class="form" :validation-schema="mySchema" autocomplete="off" #default="{ errors }" ref="formDom">
      <!-- 用户密码登录界面 -->
      <template v-if="!isMsgLogin">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field :class="{ error: errors.account }" type="text" placeholder="请输入用户名" name="account"
              v-model="form.account" />
          </div>
          <!-- 规则验证 -->
          <div class="error" v-if="errors.account"><i class="iconfont icon-warning" />{{ errors.account }}</div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <Field :class="{ error: errors.password }" type="password" placeholder="请输入密码" name="password"
              v-model="form.password" />
          </div>
          <div class="error" v-if="errors.password"><i class="iconfont icon-warning" />{{ errors.password }}</div>
        </div>
      </template>
      <!-- 短信登录界面 -->
      <template v-else>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field :class="{ error: errors.mobile }" type="text" placeholder="请输入手机号" name="mobile"
              v-model="form.mobile" />
          </div>
          <div class="error" v-if="errors.mobile"><i class="iconfont icon-warning" />{{ errors.mobile }}
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <Field type="password" placeholder="请输入验证码" name="code" v-model="form.code" />
            <span class="code" @click="send">{{ countDown === 0 ? '发送验证码' : `${countDown}后重新发送` }}</span>
          </div>
          <div class="error" v-if="errors.code"><i class="iconfont icon-warning" />{{ errors.code }}</div>
        </div>
      </template>
      <div class="form-item">
        <!-- 条款 -->
        <div class="agree">
          <!-- 复选框 -->
          <Field as="XtxCheckbox" name="isAgree" v-model="form.isAgree" />
          <span>我已同意</span>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
        <div class="error" v-if="errors.isAgree"><i class="iconfont icon-warning" />{{ errors.isAgree }}</div>
      </div>
      <!-- 登录按钮 -->
      <a href="javascript:;" class="btn" @click="loginChange()">登录</a>
    </Form>
    <!-- form表单end -->
    <!-- 底部 -->
    <div class="action">
      <a
        href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback">
        <img src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png" alt="">
      </a>
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import veeSchema from '../../utils/vee-validate-schema'
import { Form, Field } from 'vee-validate'
import { useRouter, useRoute } from 'vue-router'
import useStore from '../../store/index'
import { ref, reactive, watch, onUnmounted } from 'vue'
import { useIntervalFn } from '@vueuse/core'
import { userAccountLogin, userMobileLoginMsg, userMobileLogin } from '../../api/user'
import message from '../../components/library/message'
const router = useRouter()
// 是否短信登录
const isMsgLogin = ref(false)
// 表单信息对象
// vee-validate插件校验的基本适应步骤
// 1.导入Form, Field组件，替换form和input标签
// 2.Field需要进行数据的绑定，字段最好与返回后台的字段一样
// 3.Field的name属性指定的校验规则函数，Form的validation-schema结束校验规则对象
const form = reactive({
  // 复选框数据
  isAgree: false,
  // 用户名输入框数据
  account: 'zhousg',
  // 密码输入框数据
  password: 123456,
  // 手机号输入框数据
  mobile: null,
  // 短信验证输入框数据
  code: null
})
// 输入框校验规则对象
const mySchema = {
  account: veeSchema.account,
  password: veeSchema.password,
  mobile: veeSchema.mobile,
  code: veeSchema.code,
  isAgree: veeSchema.isAgree
}
// 切换登录方式时同时清空数据和表单验证
// 取得表达的Dom来清空规则
const formDom: any = ref(null)
watch(isMsgLogin, () => {
  // 重置复选框数据
  form.isAgree = false,
    // 重置用户名输入框数据
    form.account = null,
    // 重置密码输入框数据
    form.password = null,
    // 重置手机号输入框数据
    form.mobile = null,
    // 重置短信验证输入框数据
    form.code = null
  // 补充校验效果清除，Form组件提供resetForm()
  formDom.value.resetForm()
})
// 拿到原型的方式
// const { proxy } = getCurrentInstance()

const route: string | any = useRoute()
// 对全部表单进行统一认证
const loginChange = async () => {
  // Form组件提供了一个 validate 函数作为整体表单校验，当是返回的是一个promise
  const valid = await formDom.value.validate()
  // 返回的true为整体通过，false为不通过
  let data = null
  try {
    if (valid) {
      // 账号登录
      if (!isMsgLogin.value) {
        //  发起登录请求
        data = await userAccountLogin(form)
        // 短信登录
      } else {
        // 1.发送验证码
        // 2.核对验证码发起手机号登录请求
        data = await userMobileLogin(form)

      }
      const { id, account, avatar, nickname, mobile, token } = data.result
      // 存储到存储用户信息的pinia中
      const { user } = useStore()
      user.setUser({ id, account, avatar, nickname, mobile, token })
      // 2. 提示
      message({ type: 'success', text: '登录成功', countDown: 1500 })
      // 3. 跳转要原来页或首页
      router.push(route.query.redirectUrl || '/')
    }
  } catch (e) {
    message({ type: 'error', text: '登录失败', countDown: 1500 })
  }
}
// pause 暂停 resume 开始
// useIntervalFn(回调函数,执行间隔,是否初始化立即开启)
// 设计一个倒计时
const countDown = ref(0)
const { pause, resume } = useIntervalFn(() => {
  countDown.value--
  if (countDown.value <= 0) {
    pause()
  }
}, 1000, { immediate: false })
// 销毁组件时销毁倒计时
onUnmounted(() => {
  pause()
})

// 1.1发送验证码绑定发送事件
const send = async () => {
  const valid = mySchema.mobile(form.mobile)
  // 验证通过
  if (valid === true) {
    // 倒计时事件已经过了,才可重新发送验证码
    if (countDown.value === 0) {
      await userMobileLoginMsg(form.mobile).catch(rej => {
        console.log(rej);

        if (rej.response.status === 400) {
          message({ type: 'error', text: '用户不存在', countDown: 1500 })
        } else {
          message({ type: 'success', text: '发送成功', countDown: 1500 })
          countDown.value = 60
          resume()
        }
      }
      )

    }
  } else {
    // 验证不通过
    // 失败，使用vee的错误函数显示错误信息 setFieldError(字段,错误信息)
    formDom.value.setFieldError('mobile', valid)

  }
}
// onMounted(() => {
//   		// 组件渲染完毕，使用QC生成QQ登录按钮
//   		window.QC.Login({
//     		btnId: 'qqLoginBtn'
//       })
// 	})
</script>
<style lang="less" scoped>
@import '../../assets/styles/mixins.less';
@import '../../assets/styles/variables.less';

// 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;

    a {
      color: @xtxColor;

      i {
        font-size: 14px;
      }
    }
  }

  .form {
    padding: 0 40px;

    &-item {
      margin-bottom: 28px;

      .input {
        position: relative;
        height: 36px;

        >i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }

        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;

          &.error {
            border-color: @priceColor;
          }

          &.active,
          &:focus {
            border-color: @xtxColor;
          }
        }

        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }

      >.error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;

        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }

    .agree {
      a {
        color: #069;
      }
    }

    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;

      &.disabled {
        background: #cfcdcd;
      }
    }
  }

  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>